package fiszki.namespace;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class FiszkiDBAdapter { 
	public static final int F_ID_COLUMN = 0;
    public static final int SET_COLUMN = 1;
    public static final int QUESTION_COLUMN = 2;
    public static final int ANSWER_COLUMN = 3;
    
    private SQLiteDatabase db;
    private Context context;
    private DatabaseHelper dbHelper;
    
	public FiszkiDBAdapter(Context context) {
	    this.context = context;
	}
	
	public FiszkiDBAdapter open() {
	    dbHelper = new DatabaseHelper(context, null);
	    
	    try {
	        db = dbHelper.getWritableDatabase();
	    } 
	    catch (SQLException e) {
	        db = dbHelper.getReadableDatabase();
	    }
	    return this;
	}
	
	public void close() {
	    dbHelper.close();
	}
	
	public long addFiszka(int setID, String question, String answer) {
	    ContentValues newSetValues = new ContentValues();
	    
	    newSetValues.put("set_id", Integer.toString(setID));
	    newSetValues.put("question", question.toString());
	    newSetValues.put("answer", answer.toString());
	    
	    return db.insert("fiszki", null, newSetValues);
	}
	
	public boolean updateFiszka(int id, String question, String answer) {
	    ContentValues updateSetValues = new ContentValues();
	    
	    String where = "_id" + "=" + id;
	    updateSetValues.put("question", question.toString());
	    updateSetValues.put("answer", answer.toString());
	    
	    return db.update("fiszki", updateSetValues, where, null) > 0;
	}
	
	public boolean deleteFiszka(int id) {
	    String where = "_id" + "=" + id;	    
	    return db.delete("fiszki", where, null) > 0;
	}
	
	public Cursor getAllFiszki(int setID) {
		String where = "set_id" + "=" + setID;
	    String[] columns = { "_id", "set_id", "question", "answer" };
	    
	    return db.query("fiszki", columns, where, null, null, null, null);
	}
	 
	public FiszkaTasks getFiszka(int id) {
		String where = "_id" + "=" + id;
		String[] columns = { "_id", "set_id", "question", "answer" };
	    Cursor cursor = db.query("fiszki", columns, where, null, null, null, null);
	    FiszkaTasks task = null;
	    
	    if(cursor != null && cursor.moveToFirst()) {
	        int setID = cursor.getInt(SET_COLUMN);
	        String question = cursor.getString(QUESTION_COLUMN);
	        String answer = cursor.getString(ANSWER_COLUMN);
	        task = new FiszkaTasks(id, setID, question, answer);
	    }
	    
	    return task;
	}
}
